<template>
  <view class="wrap">
    <view
      class="content"
      :style="{ height: !isFuture() ? 'calc(100vh - 150rpx)' : 'calc(100vh - 32rpx)' }"
    >
      <view class="date-box">
        <view class="date-main" @tap="showCalendar">
          <text>{{ parseTime(selectDate, '{y}.{m}.{d}') }}</text>
          <image
            class="date-arrow"
            :style="{ transform: dateShow ? 'rotate(180deg)' : 'rotate(0deg)' }"
            src="@/static/image/date-down.png"
            mode="scaleToFill"
          />
        </view>
        <view class="calendar-box">
          <up-popup :show="dateShow" :round="16" mode="bottom" @close="closeCalendar">
            <uni-calendar
              :date="calendarSelDate"
              class="uni-calendar--hook"
              :selected="diaryedData"
              :showMonth="false"
              @change="dateConfirm"
              @monthSwitch="monthSwitch"
            />
          </up-popup>
        </view>
        <view class="week-date-box">
          <view
            :class="[
              'week-grid',
              item.date === nowDate ? 'week-today' : '',
              weekActiveIndex == index ? 'week-active' : ''
            ]"
            v-for="(item, index) in weekList"
            :key="index"
            @tap="changeWeek(item, index)"
          >
            <text class="week-name">{{ item.week }}</text>
            <text class="week-day">{{ item.day }}</text>
            <view class="week-data" v-if="item.hasDiary" />
          </view>
        </view>
      </view>
      <view class="weight-feel">
        <view class="weight-feel-title" style="margin-bottom: 40rpx">
          <text class="border" />
          <text class="name">今日减重感受</text>
        </view>
        <view class="weight-feel-title">
          <text class="sup-star">*</text>
          <text class="name">饱腹感</text>
        </view>
        <view class="satirty-box">
          <view
            @tap="selectSatiation(item)"
            :class="[
              'satirty-box-grid',
              diaryData && diaryData.satiation === item.name ? 'weight-feel-active' : ''
            ]"
            v-for="(item, index) in satirtyList"
            :key="index"
          >
            <text class="name">{{ item.name }}</text>
          </view>
        </view>

        <view class="weight-feel-title">
          <text class="sup-star">*</text>
          <text class="name">感觉</text>
        </view>
        <view class="feel-box">
          <view
            @tap="selectFeel(item)"
            :class="[
              'feel-box-grid',
              diaryData && diaryData.feeling === item.name ? 'weight-feel-active' : ''
            ]"
            v-for="(item, index) in feelList"
            :key="index"
          >
            <text class="name">{{ item.name }}</text>
          </view>
        </view>
      </view>
      <view class="weight-feel">
        <view class="weight-feel-title">
          <text class="border" />
          <text class="name">今日日记</text>
        </view>
        <view class="diary-box">
          <!-- maxlength -->
          <textarea
            v-model="diaryData.content"
            :disabled="!isEditing"
            :class="['diary-textarea', !isEditing ? 'diary-textarea-disable' : '']"
            placeholder="请输入今日日记内容"
            :maxlength="999"
          />
          <view style="margin-top: 12rpx; text-align: right">
            <text style="color: #999"> {{ inputLength }}/999 </text>
          </view>
        </view>
      </view>
      <view class="weight-feel">
        <view class="weight-feel-title">
          <text class="border" />
          <text class="name">今日照片</text>
          <text class="tips">（最多可上传9张图片）</text>
        </view>
        <view class="file-box">
          <up-upload
            :disabled="!isEditing"
            :deletable="isEditing"
            :fileList="picFileList"
            @afterRead="selectFile"
            @delete="deleteFile"
            name="3"
            multiple
            :maxCount="9"
            :previewFullImage="true"
            :maxSize="10485760"
            @oversize="handleOversize"
          />
          <!-- <up-upload
            :disabled="!isEditing"
            :fileList="picFileList"
            @afterRead="selectFile"
            @delete="deleteFile"
            name="3"
            multiple
            :maxCount="9"
            :previewFullImage="true"
          /> -->
        </view>
      </view>
    </view>
    <view class="btn-box" v-if="!isFuture()" @tap="diaryHandleBtn">
      <view class="diary-tips">
        <text> 温馨提醒：健康管理师可查看您的减重日记，请保护隐私 </text>
      </view>
      <text class="btn-text" v-if="isEditing">{{
        weekList[weekActiveIndex].hasDiary ? '再次保存' : '保存'
      }}</text>
      <text class="btn-text" v-else>编辑</text>
    </view>
  </view>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, computed } from 'vue'
import { onShow, onLoad } from '@dcloudio/uni-app'
import { parseTime } from '@/utils/tools'
import type { weekListData, diaryDataModel, filePickerImage } from './healthDiaryModel'
import { getWeekList, getDiaryList, uploadImage, saveDiary } from './healthDiary.api'

const diaryedData: any = ref([])

const satirtyList = reactive([
  {
    name: '非常饱',
    value: '1'
  },
  {
    name: '比较饱',
    value: '2'
  },
  {
    name: '刚刚好',
    value: '3'
  },
  {
    name: '稍微饿',
    value: '4'
  },
  {
    name: '非常饿',
    value: '5'
  }
])

const feelList = reactive([
  {
    name: '非常轻松',
    value: '1'
  },
  {
    name: '一般',
    value: '2'
  },
  {
    name: '不轻松',
    value: '3'
  }
])

const dateShow = ref<boolean>(false)
const nowDate = ref<string>('')
const selectDate = ref<Date>(new Date())
const currentDate = ref<Date>(new Date())
const weekList = ref<weekListData[]>([])
const WEEKDAY = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
const weekActiveIndex = ref<number>(0)
const picFileList = ref<filePickerImage[]>([])
const isEditing = ref<boolean>(false)

const diaryData = ref<diaryDataModel>({
  empi: '',
  publishTime: '',
  publishMonth: '',
  content: '',
  extParam: '',
  picList: [],
  satiation: '',
  feeling: ''
})

let userInfo: any = {}

let weekRange = {
  startTime: '',
  endTime: ''
}

let calendarSelDate: any = ''

onLoad(() => {
  userInfo = uni.getStorageSync('userInfo')
    ? JSON.parse(uni.getStorageSync('userInfo')).patientInfo
    : {}
  nowDate.value = parseTime(new Date(), '{y}-{m}-{d}')
  dateShow.value = false
  selectDate.value = new Date()
  currentDate.value = new Date()
  weekRange = getWeekRange()

  getDiaryedData()
  getDiaryInfo()
  isEditing.value = false
})

const inputLength = computed(() => {
  // 已输入的字数
  return diaryData.value.content
    ? diaryData.value.content.length > 999
      ? 999
      : diaryData.value.content.length
    : 0
})

// 获取当前周的日记填写情况
const getDiaryedData = () => {
  const params = {
    empi: userInfo.empi,
    ...weekRange
  }

  getWeekList(params).then((res) => {
    const data = res.data
    const keys: any = Object.keys(data).sort(
      (a, b) => new Date(a).getTime() - new Date(b).getTime()
    )

    weekList.value = keys.map((item: string) => {
      return {
        day: parseTime(new Date(item), '{d}'),
        date: item,
        week: WEEKDAY[new Date(item).getDay()],
        hasDiary: data[item] ? true : false
      }
    })
    isEditing.value = weekList.value[weekActiveIndex.value].hasDiary ? false : true
  })
}

// 获取当前月的日记填写情况
const getDiaryedMonthData = (date: string) => {
  const nextMonth: any = new Date(new Date(date).getFullYear(), new Date(date).getMonth() + 1, 1)

  // 获取当前月份的最后一天
  const lastDayOfCurrentMonth = new Date(nextMonth - 1)
  const lastDate = parseTime(lastDayOfCurrentMonth, '{y}-{m}-{d}')
  const params = {
    empi: userInfo.empi,
    startTime: parseTime(new Date(date), '{y}-{m}-01'),
    endTime: lastDate
  }

  getWeekList(params).then((res) => {
    const data = res.data
    const keys: any = Object.keys(data).sort(
      (a, b) => new Date(a).getTime() - new Date(b).getTime()
    )

    const hasDiaryData: any = []
    keys.map((vo) => {
      if (data[vo]) {
        hasDiaryData.push({
          date: vo,
          info: ''
        })
      }
    })
    diaryedData.value = hasDiaryData
  })
}

// 获取选中日期的日记
const getDiaryInfo = () => {
  const params = {
    empi: userInfo.empi,
    publishTime: parseTime(currentDate.value, '{y}-{m}-{d}')
  }
  picFileList.value = []

  getDiaryList(params)
    .then((res: any) => {
      if (res.data) {
        diaryData.value = res.data
        const extParam = res.data.extParam

        if (extParam) {
          diaryData.value.satiation = JSON.parse(extParam).satiation
          diaryData.value.feeling = JSON.parse(extParam).feeling
        }

        const picList = res.data.picList

        if (picList && picList.length) {
          picFileList.value = picList.map((item: any) => {
            return {
              url: item.fileUrl,
              name: item.picId,
              status: 'success',
              extname: 'png'
            }
          })
        }
      } else {
        diaryData.value = Object.assign(diaryData.value, {
          id: '',
          empi: userInfo.empi,
          publishTime: '',
          publishMonth: '',
          content: '',
          extParam: '',
          picList: [],
          satiation: '',
          feeling: ''
        })
      }
    })
    .catch((err) => {
      diaryData.value = Object.assign(diaryData.value, {
        id: '',
        empi: userInfo.empi,
        publishTime: '',
        publishMonth: '',
        content: '',
        extParam: '',
        picList: [],
        satiation: '',
        feeling: ''
      })
    })
}

// 选择图片
const selectFile = async (files: any) => {
  const lists = [].concat(files.file)

  let fileListLen = picFileList.value.length
  lists.map((item: any) => {
    picFileList.value.push({
      ...item,
      status: 'uploading',
      message: '上传中'
    })
  })

  for (let i = 0; i < lists.length; i++) {
    const result: any = await uploadImage(lists[i].url)
    const item = picFileList.value[fileListLen]
    picFileList.value.splice(fileListLen, 1, {
      ...item,
      status: 'success',
      message: '',
      url: result.data.url
    })
    fileListLen++
  }
}

// 图片大小限制
const handleOversize = (e) => {
  uni.showToast({
    title: '单张图片最大限制为10M，请重新选择',
    icon: 'none'
  })
}

// 删除
const deleteFile = (file: any) => {
  diaryData.value.picList.slice(file.index, 1)
  picFileList.value.splice(file.index, 1)
}

// 饱腹感切换
const selectSatiation = (data: any) => {
  if (isFuture()) {
    return
  } else {
    if (isEditing.value) {
      diaryData.value.satiation = data.name
    } else {
      return
    }
  }
}

const selectFeel = (data: any) => {
  if (isFuture()) {
    return
  } else {
    if (isEditing.value) {
      diaryData.value.feeling = data.name
    } else {
      return
    }
  }
}

const diaryHandleBtn = () => {
  if (!isEditing.value) {
    isEditing.value = true
  } else {
    // 保存

    const imageData = picFileList.value.map((item: any) => {
      return {
        empi: userInfo.empi,
        fileUrl: item.url
      }
    })

    if (!diaryData.value.satiation || !diaryData.value.feeling) {
      uni.showToast({
        title: '请选择今日减重感受',
        icon: 'none'
      })

      return
    }

    const data = {
      empi: userInfo.empi,
      id: diaryData.value.id ? diaryData.value.id : '',
      diaryId: diaryData.value.diaryId ? diaryData.value.diaryId : '',
      content: diaryData.value.content.substring(0, 999),
      publishTime: parseTime(currentDate.value, '{y}-{m}-{d} {h}:{i}:{s}'),
      publishMonth: parseTime(currentDate.value, '{y}{m}'),
      extParam: JSON.stringify({
        satiation: diaryData.value.satiation,
        feeling: diaryData.value.feeling
      }),
      picList: imageData
    }

    saveDiary(data).then((res) => {
      uni.showToast({
        title: '保存成功',
        success: () => {
          isEditing.value = false
          weekRange = getWeekRange()
          getDiaryedData()
          getDiaryInfo()
        }
      })
    })

    return
  }
}

const changeWeek = (item: weekListData, index: number) => {
  weekActiveIndex.value = index
  currentDate.value = new Date(item.date)
  isEditing.value = item.hasDiary ? false : true

  getDiaryInfo()
}

// 获取当前周
const getWeekRange = () => {
  const dayOfWeek = currentDate.value.getDay() // 获取今天是周几（0代表周日）
  weekActiveIndex.value = dayOfWeek

  // 计算当前周的周日（起始）
  const startOfWeek = new Date(currentDate.value)
  startOfWeek.setDate(currentDate.value.getDate() - dayOfWeek)

  // 计算当前周的周六（结束）
  const endOfWeek = new Date(startOfWeek)
  endOfWeek.setDate(startOfWeek.getDate() + 6)

  return {
    startTime: parseTime(startOfWeek, '{y}-{m}-{d}'),
    endTime: parseTime(endOfWeek, '{y}-{m}-{d}')
  }
}

const dateConfirm = (e: any) => {
  calendarSelDate = e.fulldate
  dateShow.value = false
  if (calendarSelDate) {
    currentDate.value = new Date(calendarSelDate)
    selectDate.value = new Date(calendarSelDate)
    weekRange = getWeekRange()

    getDiaryedData()
    getDiaryInfo()
  }
}
const monthSwitch = (e: any) => {
  const date = e.year + '-' + e.month + '-01'
  getDiaryedMonthData(date)
}

const showCalendar = () => {
  diaryedData.value = []
  getDiaryedMonthData(parseTime(currentDate.value, '{y}-{m}-{d}'))
  nextTick(() => {
    dateShow.value = true
  })
}

const closeCalendar = () => {
  dateShow.value = false
  // dateShow.value = false
  // if (calendarSelDate) {
  //   currentDate.value = new Date(calendarSelDate)
  //   selectDate.value = new Date(calendarSelDate)
  //   weekRange = getWeekRange()
  //   getDiaryedData()
  //   getDiaryInfo()
  // }
}

const isFuture = () => {
  if (
    weekList.value.length > 0 &&
    new Date(weekList.value[weekActiveIndex.value].date).getTime() >
      new Date(parseTime(new Date(), '{y}-{m}-{d}')).getTime()
  ) {
    return true
  } else {
    return false
  }
}
</script>
<style lang="scss" scoped>
.wrap {
  position: relative;
  height: 100vh;
  overflow: hidden;
}

.content {
  height: calc(100vh - 220rpx);
  overflow-y: scroll;
}

.date-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 26rpx 0 32rpx;
}

.date-main {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  height: 60rpx;
  padding: 16rpx 32rpx;
  margin-bottom: 24rpx;
  font-size: 28rpx;
  color: #222;
  background: #fff;
  border-radius: 38rpx;
}

.date-arrow {
  width: 24rpx;
  height: 24rpx;
  margin-left: 16rpx;
  transition: transform 0.3s;
}

.week-date-box {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  grid-gap: 16rpx;
}

.week-grid {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 84rpx;
  height: 110rpx;
  background: rgb(255 255 255 / 80%);
  border: 1rpx solid #fff;
  border-radius: 8rpx;

  .week-name {
    font-size: 28rpx;
    font-weight: 700;
    color: #222;
  }

  .week-day {
    margin: 8rpx 0;
    font-size: 26rpx;
    font-weight: 400;
    color: #666;
  }

  .week-data {
    width: 8rpx;
    height: 8rpx;
    background: #00d1b6;
    border-radius: 50%;
  }
}

.week-today {
  background: rgb(255 255 255 / 80%);
  border: 1rpx solid #00d1b6;
  transform: rotateZ(360deg);

  .week-name {
    color: #00d1b6;
  }

  .week-day {
    color: #00d1b6;
  }
}

.week-active {
  background: #00d1b6;

  .week-name {
    color: #fff;
  }

  .week-day {
    color: #fff;
  }
}

.weight-feel {
  position: relative;
  z-index: 1;
  width: 100%;
  padding: 32rpx;
  margin-bottom: 32rpx;
  background: #fff;
  border-radius: 24rpx;

  .header-box {
    position: absolute;
    top: -26rpx;
    left: 0;
    z-index: 2;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    width: 311rpx;
    height: 84rpx;
    background: linear-gradient(118deg, #fef4d1 0%, #fce8b5 100%);
    border-radius: 24rpx 0;

    .header-box-image {
      width: 37.09rpx;
      height: 37.09rpx;
      margin-right: 10rpx;
    }

    .header-box-title {
      font-size: 32rpx;
      font-weight: 700;
      color: #693d14;
    }
  }
}

.weight-feel-title {
  display: flex;
  align-items: center;
  margin-bottom: 24rpx;

  .border {
    display: inline-block;
    width: 8rpx;
    height: 32rpx;
    margin-right: 18rpx;
    background: #00d1b6;
    border-radius: 0 6rpx 6rpx 0;
  }

  .name {
    margin-right: 8rpx;
    font-size: 32rpx;
    font-weight: 700;
    color: #222;
  }

  .tips {
    font-size: 24rpx;
    font-weight: 400;
    color: #666;
  }
}

.satirty-box {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  grid-gap: 16rpx;
  margin-bottom: 40rpx;

  .satirty-box-grid {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 124rpx;
    height: 124rpx;
    background: #fafafa;
    border: 1rpx solid #e5e6eb;
    border-radius: 8rpx;

    .name {
      font-size: 28rpx;
      font-weight: 700;
      color: #222;
    }
  }
}

.feel-box {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  grid-gap: 16rpx;

  .feel-box-grid {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 218rpx;
    height: 124rpx;
    background: #fafafa;
    border: 1rpx solid #e5e6eb;
    border-radius: 8rpx;

    .name {
      font-size: 28rpx;
      font-weight: 700;
      color: #222;
    }
  }
}

.diary-box {
  // margin-bottom: 48rpx;

  .diary-textarea {
    width: 96%;
    padding: 18rpx 2%;
    font-size: 30rpx;
    color: #222;
    border: 1rpx solid #e5e6eb;
    border-radius: 8rpx;
  }

  .diary-textarea-disable {
    color: #999;
    background-color: #fafafa;
  }
}

.file-box {
  margin-bottom: 16rpx;
}

.diary-tips {
  margin-bottom: 24rpx;
  font-size: 24rpx;
  font-weight: 400;
  color: #999;
  text-align: left;
  text-align: center;
}

.btn-box {
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 100;
  width: 100%;
  height: 186rpx;
  padding: 24rpx 32rpx 0;
  // margin-top: 76rpx;
  // margin-bottom: 24rpx;
  text-align: center;
  background: #fff;

  .btn-text {
    display: inline-block;
    width: 100%;
    height: 88rpx;
    font-size: 32rpx;
    font-weight: 700;
    line-height: 88rpx;
    color: #fff;
    background: #00d1b6;
    border-radius: 44rpx;
  }
}

.weight-feel-active {
  background: #00d1b6 !important;

  .name {
    color: #fff !important;
  }
}

::v-deep .uni-calendar-item--isDay {
  background-color: #00d1b6 !important;
}

::v-deep .uni-calendar-item--checked {
  background-color: #00d1b6 !important;
}

::v-deep .uni-date-editor {
  width: 254rpx;
  margin: 0 auto;
}

// ::v-deep .uni-calendar-item--isDay-text {
//   background-color: #00d1b6 !important;
// }

::v-deep .uni-calendar-item--isDay .uni-calendar-item--isDay-text {
  color: #fff;
}

::v-deep .uni-calendar-item__weeks-box-circle {
  background-color: #00d1b6 !important;
}

::v-deep .uni-calendar-item__weeks-box .uni-calendar-item--checked {
  background-color: #00d1b6 !important;
}

::v-deep .uni-calendar__weeks-day {
  background: #ebfbf9;

  .uni-calendar__weeks-day-text {
    color: #00d1b6 !important;
  }
}

::v-deep .uni-datetime-picker--btn {
  background-color: #00d1b6 !important;
}

.sup-star {
  color: red;
}
</style>

<style>
.icon-add {
  width: 50rpx !important;
  height: 4rpx !important;
}

.file-picker__box-content {
  border: 2rpx solid #e5e6eb !important;
  border-radius: 4rpx !important;
}

.icon-del-box {
  top: 0 !important;
  right: 0 !important;
  width: 32rpx !important;
  height: 32rpx !important;
  background-color: rgb(0 0 0 / 31%) !important;
  border-radius: 0 0 0 12rpx !important;
  transform: rotate(0deg) !important;
}

.icon-del-box .icon-del {
  transform: rotate(45deg) !important;
}

.icon-del-box .rotate {
  transform: rotate(135deg) !important;
}

/* .calendar-box .u-fade-enter-active,
.calendar-box .u-fade-leave-active {
  top: 110rpx !important;
}

.calendar-box .u-slide-down-enter-active,
.calendar-box .u-slide-down-leave-active,
.calendar-box .u-slide-left-enter-active,
.calendar-box .u-slide-left-leave-active,
.calendar-box .u-slide-right-enter-active,
.calendar-box .u-slide-right-leave-active,
.calendar-box .u-slide-up-enter-active,
.calendar-box .u-slide-up-leave-active {
  top: 110rpx !important;
} */

.calendar-box .uni-calendar__content {
  border-radius: 24rpx 24rpx 0;
}

/* .calendar-box .uni-calendar-item--isDay-text {
  color: #fff !important;
} */

.calendar-box .uni-calendar__backtoday {
  background-color: rgb(0 209 182 / 5%);
}

.calendar-box .uni-calendar-item__weeks-box-item .uni-calendar-item--isDay-text {
  color: #00d1b6 !important;
}

.calendar-box .uni-calendar-item--isDay .uni-calendar-item--isDay-text {
  color: #fff !important;
}

.calendar-box .uni-calendar__header-text {
  font-size: 36rpx !important;
  font-weight: 700;
  color: #222 !important;
}

.calendar-box .uni-calendar-item__weeks-box-circle {
  top: 42px !important;
  right: 50% !important;
  margin-right: -4px;
}

/* .calendar-box .uni-calendar-item--disable {
  background-color: transparent;
} */
</style>
